package yx.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yx.dao.BaseDaoInt;
import yx.model.BsAttendance;
import yx.model.BsCourse;
import yx.model.BsGrade;
import yx.model.BsStudent;
import yx.model.SmCode;
import yx.utils.DateUtils;
import yx.utils.FileUtils;
import yx.vo.AttendanceVO;
import yx.vo.DatagridVO;
import yx.vo.GradeVO;

@Service("attendanceService")
public class AttendanceServiceImpl implements AttendanceServiceInt {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AttendanceServiceImpl.class);

	private BaseDaoInt<BsAttendance> attendanceDao;
	private BaseDaoInt<BsStudent> studentDao;
	private BaseDaoInt<BsCourse> courseDao;
	private BaseDaoInt<SmCode> codeDao;

	public BaseDaoInt<BsAttendance> getAttendanceDao() {
		return attendanceDao;
	}

	@Autowired
	public void setAttendanceDao(BaseDaoInt<BsAttendance> attendanceDao) {
		this.attendanceDao = attendanceDao;
	}

	public BaseDaoInt<BsStudent> getStudentDao() {
		return studentDao;
	}

	@Autowired
	public void setStudentDao(BaseDaoInt<BsStudent> studentDao) {
		this.studentDao = studentDao;
	}

	public BaseDaoInt<BsCourse> getCourseDao() {
		return courseDao;
	}

	@Autowired
	public void setCourseDao(BaseDaoInt<BsCourse> courseDao) {
		this.courseDao = courseDao;
	}

	public BaseDaoInt<SmCode> getCodeDao() {
		return codeDao;
	}

	@Autowired
	public void setCodeDao(BaseDaoInt<SmCode> codeDao) {
		this.codeDao = codeDao;
	}

	@Override
	public AttendanceVO save(AttendanceVO attendance) {
		BsAttendance t = new BsAttendance();
		BeanUtils.copyProperties(attendance, t);
		attendanceDao.save(t);
		BeanUtils.copyProperties(t, attendance);
		// 转换学生名称
		BsStudent stu = studentDao.get(BsStudent.class, attendance.getStudentId());
		attendance.setStudentName(stu.getStudentName());
		attendance.setStudentNo(stu.getStudentNo());
		// 转换课程名称
		BsCourse course = courseDao.get(BsCourse.class, attendance.getCourseId());
		attendance.setCourseName(course.getCourseName());
		// 出勤情况
		if (attendance.getAttendanceFlag() != null && !"".equals(attendance.getAttendanceFlag())) {
			Map<String, String> retMap = getAttendanceAndLeave("05");
			attendance.setAttendanceFlagName(retMap.get(attendance.getAttendanceFlag()));
		}
		// 请假情况
		if (attendance.getLeaveFlag() != null && !"".equals(attendance.getLeaveFlag())) {
			Map<String, String> retMap = getAttendanceAndLeave("06");
			attendance.setLeaveFlagName(retMap.get(attendance.getLeaveFlag()));
		}
		// 授课时段
		if (attendance.getClassType() != null && !"".equals(attendance.getClassType())) {
			Map<String, String> retMap = getAttendanceAndLeave("07");
			attendance.setClassTypeName(retMap.get(attendance.getClassType()));
		}
		attendance.setTeachingDateStr(DateUtils.formateDateToString(attendance.getTeachingDate(), null));
		return attendance;
	}
	
	@Override
	public void saveAll(List<BsAttendance> list) {
		for (BsAttendance t : list) {
			attendanceDao.save(t);
		}
	}

	@Override
	public DatagridVO datagrid(AttendanceVO attendance) {
		DatagridVO dg = new DatagridVO();
		String hql = "from BsAttendance g, BsCourse c, BsStudent s where c.id = g.courseId and s.id = g.studentId";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(attendance, hql, params);
		String totalHql = "select count(*) " + hql;
		hql = addOrder(attendance, hql);
		List l = attendanceDao.find(hql, params, attendance.getPage(), attendance.getRows());
		List<AttendanceVO> nl = new ArrayList<AttendanceVO>();
		changeModel(l, nl);
		dg.setTotal(attendanceDao.count(totalHql, params));
		dg.setRows(nl);
		return dg;
	}

	private void changeModel(List l, List<AttendanceVO> nl) {
		if (l != null && l.size() > 0) {
			Map<String, String> retMap = getAttendanceAndLeave("05");
			Map<String, String> retMap2 = getAttendanceAndLeave("06");
			Map<String, String> retMap3 = getAttendanceAndLeave("07");
			for (int i = 0; i < l.size(); i++) {
				Object[] obj = (Object[]) l.get(i);
				BsAttendance g = (BsAttendance) obj[0];
				BsCourse c = (BsCourse) obj[1];
				BsStudent s = (BsStudent) obj[2];

				AttendanceVO vo = new AttendanceVO();
				BeanUtils.copyProperties(g, vo);
				vo.setStudentId(s.getId());
				vo.setStudentName(s.getStudentName());
				vo.setStudentNo(s.getStudentNo());
				vo.setCourseId(c.getId());
				vo.setCourseName(c.getCourseName());
				// 出勤情况
				if (vo.getAttendanceFlag() != null && !"".equals(vo.getAttendanceFlag())) {
					vo.setAttendanceFlagName(retMap.get(vo.getAttendanceFlag()));
				}
				// 出勤情况
				if (vo.getLeaveFlag() != null && !"".equals(vo.getLeaveFlag())) {
					vo.setLeaveFlagName(retMap2.get(vo.getLeaveFlag()));
				}
				// 授课时段
				if (vo.getClassType() != null && !"".equals(vo.getClassType())) {
					vo.setClassTypeName(retMap3.get(vo.getClassType()));
				}
				vo.setTeachingDateStr(DateUtils.formateDateToString(vo.getTeachingDate(), null));
				nl.add(vo);
			}
		}
	}

	private String addOrder(AttendanceVO attendance, String hql) {
		if (attendance.getSort() != null || attendance.getOrder() != null) {
			hql += " order by " + attendance.getSort() + " " + attendance.getOrder();
		}
		return hql;
	}

	private String addWhere(AttendanceVO attendance, String hql, Map<String, Object> params) {
		if (attendance.getStudentName() != null && !"".equals(attendance.getStudentName().trim())) {
			hql += " and s.studentName like :studentName";
			params.put("studentName", "%%" + attendance.getStudentName().trim() + "%%");
		}
		if (attendance.getStudentNo() != null && !"".equals(attendance.getStudentNo().trim())) {
			hql += " and s.studentNo = :studentNo";
			params.put("studentNo", attendance.getStudentNo().trim());
		}
		if (attendance.getCourseName() != null && !"".equals(attendance.getCourseName().trim())) {
			hql += " and c.courseName like :courseName";
			params.put("courseName", "%%" + attendance.getCourseName().trim() + "%%");
		}
		return hql;
	}

	@Override
	public void remove(String ids) {
		String[] nids = ids.split(",");
		String hql = "delete BsAttendance t where t.id in (";
		for (int i = 0; i < nids.length; i++) {
			if (i > 0) {
				hql += ",";
			}
			hql += "'" + nids[i] + "'";
		}
		hql += ")";
		attendanceDao.executeHql(hql);
	}

	@Override
	public AttendanceVO edit(AttendanceVO attendance) {
		BsAttendance t = attendanceDao.get(BsAttendance.class, attendance.getId());
		BeanUtils.copyProperties(attendance, t);
		// 转换学生名称
		BsStudent stu = studentDao.get(BsStudent.class, attendance.getStudentId());
		attendance.setStudentName(stu.getStudentName());
		attendance.setStudentNo(stu.getStudentNo());
		// 转换课程名称
		BsCourse course = courseDao.get(BsCourse.class, attendance.getCourseId());
		attendance.setCourseName(course.getCourseName());
		// 出勤情况
		if (attendance.getAttendanceFlag() != null && !"".equals(attendance.getAttendanceFlag())) {
			Map<String, String> retMap = getAttendanceAndLeave("05");
			attendance.setAttendanceFlagName(retMap.get(attendance.getAttendanceFlag()));
		}
		// 出勤情况
		if (attendance.getLeaveFlag() != null && !"".equals(attendance.getLeaveFlag())) {
			Map<String, String> retMap = getAttendanceAndLeave("06");
			attendance.setLeaveFlagName(retMap.get(attendance.getLeaveFlag()));
		}
		// 授课时段
		if (attendance.getClassType() != null && !"".equals(attendance.getClassType())) {
			Map<String, String> retMap = getAttendanceAndLeave("07");
			attendance.setClassTypeName(retMap.get(attendance.getClassType()));
		}
		attendance.setTeachingDateStr(DateUtils.formateDateToString(attendance.getTeachingDate(), null));
		return attendance;
	}

	private Map<String, String> getAttendanceAndLeave(String type) {
		Map<String, String> retMap = new HashMap<String, String>();
		if (type != null && !"".equals(type)) {
			String hql = "from SmCode t where t.ctype = :ctype";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("ctype", type);
			List<SmCode> l = codeDao.find(hql, params);
			for (SmCode c : l) {
				retMap.put(c.getCvalue(), c.getCname());
			}
		}
		return retMap;
	}

	@Override
	public List<AttendanceVO> queryAttendanceByStudentAndCourse(AttendanceVO attendance) {
		String hql = "from BsAttendance s where s.studentId = :studentId and s.courseId = :courseId and s.teachingDate =:teachingDate and s.classType =:classType";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("studentId", attendance.getStudentId());
		params.put("courseId", attendance.getCourseId());
		params.put("teachingDate", attendance.getTeachingDate());
		params.put("classType", attendance.getClassType());
		List<BsAttendance> list = attendanceDao.find(hql, params);
		List<AttendanceVO> retList = new ArrayList<AttendanceVO>();
		if (list != null && list.size() != 0) {
			for (BsAttendance t : list) {
				AttendanceVO u = new AttendanceVO();
				BeanUtils.copyProperties(t, u);
				retList.add(u);
			}
		}
		return retList;
	}
	
	/**
	 * 获得文件字节
	 */
	public byte[] getFileBytes(String fullFilePath) {
		if (fullFilePath == null || "".equals(fullFilePath)) {
			logger.info("指定的文件不存在！");
			return new byte[] {};
		}
		File file = new File(fullFilePath);
		if (!file.exists()) {
			logger.info("指定的文件不存在！");
			return new byte[] {};
		}
		return FileUtils.readFile(file);
	}
	
}
